/*
 * Copyright 2010 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
// http://www.java2s.com/Open-Source/Android/App/androidto/com/google/android/apps/iosched/service/SyncService.java.htm

package fr.enseirb.mycub.service;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.zip.GZIPInputStream;

import org.apache.http.Header;
import org.apache.http.HeaderElement;
import org.apache.http.HttpEntity;
import org.apache.http.HttpRequest;
import org.apache.http.HttpRequestInterceptor;
import org.apache.http.HttpResponse;
import org.apache.http.HttpResponseInterceptor;
import org.apache.http.client.HttpClient;
import org.apache.http.entity.HttpEntityWrapper;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.HttpContext;

import fr.enseirb.mycub.PrefManager;
import fr.enseirb.mycub.activity.AbstractPreferencesActivity;
import fr.enseirb.mycub.json.JSONHandler;
import fr.enseirb.mycub.json.impl.BikeStationJSONHandler;
import fr.enseirb.mycub.json.impl.BusStationFullJSONHandler;
import fr.enseirb.mycub.json.impl.InternetFullJSONHandler;
import fr.enseirb.mycub.json.impl.ParkingFullJSONHandler;
import fr.enseirb.mycub.json.impl.TramStationFullJSONHandler;

import android.app.IntentService;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.Resources;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.ResultReceiver;
import android.text.format.DateUtils;
import android.util.Log;


/**
 * Background {@link Service} that synchronizes data living in
 * {@link ScheduleProvider}. Reads data from both local {@link Resources} and
 * from remote sources, such as a spreadsheet.
 */
public class UpdateService extends IntentService {

	public static final String EXTRA_STATUS_RECEIVER = "fr.enseirb.mycub.extra.STATUS_RECEIVER";
	public static final String EXTRA_RESULT = "extra_result";
	public static final String EXTRA_RESULT2 = "extra_result";

	public static final String ACTION_ADD_BIKE = "action_add_bike";
	public static final String ACTION_DELETE_BIKE = "action_delete_bike";
	
	public static final String ACTION_ADD_TRAM = "action_add_tram";
	public static final String ACTION_DELETE_TRAM = "action_delete_tram";
	
	public static final String ACTION_ADD_BUS = "action_add_bus";
	public static final String ACTION_DELETE_BUS = "action_delete_bus";
	
	public static final String ACTION_ADD_PARKING = "action_add_parking";
	public static final String ACTION_DELETE_PARKING = "action_delete_parking";
	
	public static final String ACTION_ADD_INTERNET = "action_add_internet";
	public static final String ACTION_DELETE_INTERNET = "action_delete_internet";
	
	public static final String ACTION_REFRESH = "action_refresh";
	public static final String ACTION_FORCED_REFRESH = "action_forced_refresh";
	public static final String ACTION_CLEAR_UPDATES = "clear_updates";

	public static final int STATUS_UPDATED = 0x1;
	public static final int STATUS_ERROR = 0x2;

	private static final int SECOND_IN_MILLIS = (int) DateUtils.SECOND_IN_MILLIS;

	private static final String HEADER_ACCEPT_ENCODING = "Accept-Encoding";
	private static final String ENCODING_GZIP = "gzip";

	private static final ArrayList<JSONHandler> jsonHandlers = new ArrayList<JSONHandler>();
	public static long minIntervalUntilNextUpdate = 5000; //DEFAULT VALUE

	public UpdateService() {
		super("MyCub Update service");
	}

	@SuppressWarnings("unchecked")
	@Override
	protected void onHandleIntent(Intent intent) {
		Log.i("UpdateService","handleIntent");
		//Verif Connectivite
		NetworkInfo activeNetwork = ((ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();
		final ResultReceiver receiver = intent
				.getParcelableExtra(EXTRA_STATUS_RECEIVER);
		Bundle bundle = new Bundle();
		int status = STATUS_ERROR;
		if (activeNetwork == null || !activeNetwork.isConnectedOrConnecting()) {
			Log.i("NO NETWORK", "NO INTERNET");
			bundle = new Bundle();
			bundle.putString(Intent.EXTRA_TEXT, "No network connectivity");
			//receiver.send(STATUS_ERROR, bundle);
			return;
		}
		// on est connecte
		String action = intent.getAction();
			/** 
			 * 
			 * 								BIKE
			 * 
			 */
			//Mise a jour Bike
			if(ACTION_ADD_BIKE.equals(action)) {
				addJsonHandler(new BikeStationJSONHandler(this));
			}
			else if(ACTION_DELETE_BIKE.equals(action)){
				for(int i = 0; i < jsonHandlers.size(); i++){
					if(jsonHandlers.get(i) instanceof BikeStationJSONHandler){
						Log.e("UpdateService", " removed bike");
						jsonHandlers.remove(i);
					}
				}
			}
			
			/** 
			 * 
			 * 								TRAM
			 * 
			 */
			//Mise a jour Tram
			if(ACTION_ADD_TRAM.equals(action)) {
				addJsonHandler(new TramStationFullJSONHandler(this));
			}
			else if(ACTION_DELETE_TRAM.equals(action)){
				for(int i = 0; i < jsonHandlers.size(); i++){
					if(jsonHandlers.get(i) instanceof TramStationFullJSONHandler){
						Log.e("UpdateService", " removed tram");
						jsonHandlers.remove(i);
					}
				}
			}
			
			/** 
			 * 
			 * 								BUS
			 * 
			 */
			//Mise a jour Bus
			if(ACTION_ADD_BUS.equals(action)) {
				addJsonHandler(new BusStationFullJSONHandler(this));
			}
			else if(ACTION_DELETE_BUS.equals(action)){
				for(int i = 0; i < jsonHandlers.size(); i++){
					if(jsonHandlers.get(i) instanceof BusStationFullJSONHandler){
						Log.e("UpdateService", " removed bus");
						jsonHandlers.remove(i);
					}
				}
			}
			
			/** 
			 * 
			 * 								PARKING
			 * 
			 */
			if(ACTION_ADD_PARKING.equals(action)) {
				addJsonHandler(new ParkingFullJSONHandler(this));
			}
			else if(ACTION_DELETE_PARKING.equals(action)){
				for(int i = 0; i < jsonHandlers.size(); i++){
					if(jsonHandlers.get(i) instanceof ParkingFullJSONHandler){
						jsonHandlers.remove(i);
					}
				}
			}
			
			
			/** 
			 * 
			 * 								Internet
			 * 
			 */
			if(ACTION_ADD_INTERNET.equals(action)) {
				addJsonHandler(new InternetFullJSONHandler(this));
			}
			else if(ACTION_DELETE_INTERNET.equals(action)){
				for(int i = 0; i < jsonHandlers.size(); i++){
					if(jsonHandlers.get(i) instanceof InternetFullJSONHandler){
						jsonHandlers.remove(i);
					}
				}
			}
			
			else if(ACTION_REFRESH.equals(action)){
				checkForUpdates(false);
			}
			else if(ACTION_FORCED_REFRESH.equals(action)){
				checkForUpdates(true);
			}
			else if(ACTION_CLEAR_UPDATES.equals(action)){
				for(int i = 0; i < jsonHandlers.size(); i++){
						jsonHandlers.remove(i);
				}
			}
			
	}

	public void checkForUpdates(boolean forced){
		Log.i("UpdateService", "checkForUpdates handlers : "+jsonHandlers.size());
		for(int i = 0; i < jsonHandlers.size(); i++){
			JSONHandler jsonHandler = jsonHandlers.get(i);
			jsonHandler.update(forced);
		}
	}

	public void addJsonHandler(JSONHandler handler){
		jsonHandlers.add(handler);
		checkForUpdates(false);
	}

	public void removeJsonHandler(JSONHandler handler){
		jsonHandlers.remove(handler);
	}


	/**
	 * Generate and return a {@link HttpClient} configured for general use,
	 * including setting an application-specific user-agent string.
	 */
	public static HttpClient getHttpClient(Context context) {
		final HttpParams params = new BasicHttpParams();

		// Use generous timeouts for slow mobile networks
		HttpConnectionParams
		.setConnectionTimeout(params, 20 * SECOND_IN_MILLIS);
		HttpConnectionParams.setSoTimeout(params, 20 * SECOND_IN_MILLIS);

		HttpConnectionParams.setSocketBufferSize(params, 8192);
		HttpProtocolParams.setUserAgent(params, buildUserAgent(context));

		final DefaultHttpClient client = new DefaultHttpClient(params);

		client.addRequestInterceptor(new HttpRequestInterceptor() {
			public void process(HttpRequest request, HttpContext context) {
				// Add header to accept gzip content
				if (!request.containsHeader(HEADER_ACCEPT_ENCODING)) {
					request.addHeader(HEADER_ACCEPT_ENCODING, ENCODING_GZIP);
				}
			}
		});

		client.addResponseInterceptor(new HttpResponseInterceptor() {
			public void process(HttpResponse response, HttpContext context) {
				// Inflate any responses compressed with gzip
				final HttpEntity entity = response.getEntity();
				final Header encoding = entity.getContentEncoding();
				if (encoding != null) {
					for (HeaderElement element : encoding.getElements()) {
						if (element.getName().equalsIgnoreCase(ENCODING_GZIP)) {
							response.setEntity(new InflatingEntity(response
									.getEntity()));
							break;
						}
					}
				}
			}
		});

		return client;
	}

	/**
	 * Build and return a user-agent string that can identify this application
	 * to remote servers. Contains the package name and version code.
	 */
	private static String buildUserAgent(Context context) {
		try {
			final PackageManager manager = context.getPackageManager();
			final PackageInfo info = manager.getPackageInfo(context
					.getPackageName(), 0);

			// Some APIs require "(gzip)" in the user-agent string.
			return info.packageName + "/" + info.versionName + " ("
			+ info.versionCode + ") (gzip)";
		} catch (NameNotFoundException e) {
			return null;
		}
	}

	/**
	 * Simple {@link HttpEntityWrapper} that inflates the wrapped
	 * {@link HttpEntity} by passing it through {@link GZIPInputStream}.
	 */
	private static class InflatingEntity extends HttpEntityWrapper {
		public InflatingEntity(HttpEntity wrapped) {
			super(wrapped);
		}

		@Override
		public InputStream getContent() throws IOException {
			return new GZIPInputStream(wrappedEntity.getContent());
		}

		@Override
		public long getContentLength() {
			return -1;
		}
	}
}
